package live.ifox.stage;

import android.content.Intent;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import com.google.zxing.Result;

import live.ifox.factory.ID;
import me.dm7.barcodescanner.zxing.ZXingScannerView;

public class CodeScanner extends AppCompatActivity implements ZXingScannerView.ResultHandler {
    private ZXingScannerView mScannerView;

    @Override
    public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
        super.onCreate(savedInstanceState, persistentState);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mScannerView = new ZXingScannerView(CodeScanner.this);   // Programmatically initialize the scanner stage
        setContentView(mScannerView);

        mScannerView.setResultHandler(CodeScanner.this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();         // Start camera
        mScannerView.setAutoFocus(true);    // 设置自动对焦
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mScannerView != null && mScannerView.isActivated()) {
            mScannerView.stopCamera();
        }
    }

    @Override
    public void handleResult(Result result) {
        // Do something with the result here
        // Log.e("handler", result.getText()); // Prints scan results
        // Log.e("handler", result.getBarcodeFormat().toString()); // Prints the scan format (qrcode)

        Intent intent = new Intent();
        intent.putExtra("code", result.getText());
        setResult(ID.RESULT_DONE, intent);
        finish();

        // show the scanner result into dialog box.
        /*
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result").setMessage(result.getText());
        builder.create().show();
        */
        // If you would like to resume scanning, call this method below:
        // mScannerView.resumeCameraPreview(this);
    }
}